#include "mainwindow.h"
#include "ui_mainwindow.h"



MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    initMainWindow();

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::initMainWindow() {

    connect(ui->send_pushButton, &QPushButton::clicked, this, &MainWindow::on_sendPushButton_clicked);
    connect(ui->search_pushButton, &QPushButton::clicked, this, &MainWindow::on_searchPushButton_clicked);

    myUdpSocket = new QUdpSocket(this);
    myUdpPort = 23232;
    if (!myUdpSocket->bind(myUdpPort, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint)) {
        qDebug() << "fail to bind socket to port";
    }

    connect(myUdpSocket, SIGNAL(readyRead()), this, SLOT(recvAndProcessChatMsg()));

    myfsrv = new FileSrvDlg(this);

    //connect(myfsrv, SIGNAL(sendFileName(QString)), this, SLOT(getSfileName(QString)));
}

void MainWindow::on_searchPushButton_clicked() {
    myname = this->windowTitle();
    ui->usrList_label->setText(myname);
    sendChatMsg(OnLine);
}

void MainWindow::sendChatMsg(ChatMsgType msgType, QString rmtName) {
    QByteArray qba;
    QDataStream write(&qba, QIODevice::WriteOnly);

    QString locHostIp = getLocHostIp();
    //QString locChatMsg = getLocChatMsg();
    QString locChatMsg = "hello";

    write << msgType << myname;

    switch (msgType) {
    case ChatMsg:
        write << locHostIp << locChatMsg;
        break;
    case OnLine:
        write << locHostIp;
        break;
    case OffLine:

        break;
    case SfileName:
        write << locHostIp << rmtName << myFileName;
        break;
    case RefFile:
        write << locHostIp << rmtName;
        break;

    default:
        break;
    }

    qint64 is_write = myUdpSocket->writeDatagram(qba, qba.length(), QHostAddress::Broadcast, myUdpPort);

    if (is_write == -1) {
        qDebug() << "fail to send msg!";
    }
}

void MainWindow::recvAndProcessChatMsg() {
    while(myUdpSocket->hasPendingDatagrams()) {
        QByteArray qba;
        qba.resize(myUdpSocket->pendingDatagramSize());
        myUdpSocket->readDatagram(qba.data(), qba.size());

        QDataStream read(&qba, QIODevice::ReadOnly);

        int msgType;
        read >> msgType;
        QString name, hostip, chatmsg, rname, fname;
        QString curtime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");

        switch (msgType) {
        case ChatMsg:{

            read >> name >> hostip >> chatmsg;
            ui->message_textBrowser->setTextColor(Qt::darkGreen);
            ui->message_textBrowser->setCurrentFont(QFont("Times New Roman"));
            ui->message_textBrowser->append("【" + name + "】" + curtime);
            ui->message_textBrowser->append(chatmsg);
            break;
        }
        case OnLine:
            read >> name >> hostip;
            onLine(name, curtime);
            break;
        case OffLine:
            read >> name;
            offLine(name, curtime);
            break;
        case SfileName:
            read >> name >> hostip >> rname >> fname;
            //recvFileName(name, hostip, rname, fname);
            break;
        case RefFile:
            read >> name >> hostip >> rname;
            //if (myname == rname) myfsrv->cntRefused();
        default:
            break;
        }
    }
}

void MainWindow::onLine(QString name, QString time) {
    bool notExist = ui->usrList_tableWidget->findItems(name, Qt::MatchExactly).isEmpty();

    if (notExist) {
        QTableWidgetItem *newuser = new QTableWidgetItem(name);
        ui->usrList_tableWidget->insertRow(0);
        ui->usrList_tableWidget->setItem(0, 0, newuser);
        ui->message_textBrowser->setTextColor(Qt::gray);
        ui->message_textBrowser->setCurrentFont(QFont("Times New Roman", 12));
        ui->message_textBrowser->append(tr("%1 %2 上线！").arg(time).arg(name));
        sendChatMsg(OnLine);
    }
}

void MainWindow::offLine(QString name, QString time) {
    int row = ui->usrList_tableWidget->findItems(name, Qt::MatchExactly).first()->row();
    ui->usrList_tableWidget->removeRow(row);
    ui->message_textBrowser->setTextColor(Qt::gray);
    ui->message_textBrowser->setCurrentFont(QFont("Times New Roman", 12));
    ui->message_textBrowser->append(tr("%1 %2 离线！").arg(time).arg(name));
}

void MainWindow::closeEvent(QCloseEvent *event) {
    sendChatMsg(OffLine);
}

QString MainWindow::getLocHostIp() {
    QList<QHostAddress> addrlist = QNetworkInterface::allAddresses();
    foreach (QHostAddress addr, addrlist) {
        if (addr.protocol() == QAbstractSocket::IPv4Protocol)
            return addr.toString();
    }

    return 0;
}

QString MainWindow::getLocChatMsg() {
    QString chatmsg = ui->message_textEdit->toHtml();
    ui->message_textEdit->clear();
    ui->message_textEdit->setFocus();

    return chatmsg;
}

void MainWindow::on_sendPushButton_clicked() {
    sendChatMsg(ChatMsg);
}
